/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.web30.nntp.sync;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.web30.nntp.service.NNTPService;
import org.web30.nntp.service.NNTPService.NewsRecords;

/**
 *
 * @author xjzhou
 */
public class NNTPResource extends HttpServlet {

    private static final String CONTENT_TYPE = "text/html";
    private static Logger logger = Logger.getLogger(NNTPResource.class.getName());
    private static FileHandler fh = null;
    public static final String DEFAULT_ENCODING = "ISO-8859-1";

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            NNTPResource.fh = new FileHandler("/opt/xiazy/xjlog.txt");
            logger.addHandler(fh);
            logger.setLevel(Level.ALL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        NNTPService srv = new NNTPService("localhost", 7500, "xutj@nec-as.nec.com.cn", "eds321");
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType(CONTENT_TYPE);

        String group = request.getParameter("group");
        String lastsyncid = request.getParameter("lastsyncid");
        if (group == null) {
            response.sendError(400, "group name is empty!");
        }
        srv.init();
        srv.setOmmitKey("ReplicaFrom");
        srv.setOmmitValue("isReplica");
        NewsRecords records;
        if (lastsyncid != null && lastsyncid.length() > 0) {
            lastsyncid = "<" + lastsyncid + ">";
            records = srv.getNewNews(group, lastsyncid);
            logger.info("last sync id : " + lastsyncid);
        } else {
            records = srv.getNewNews(group);
            logger.info("group name: " + group);
        }

        BufferedReader br;
        PrintWriter out = response.getWriter();
        if (!records.hasNext()) {
            logger.severe("out stream is null");
            response.setStatus(204);
        }
        if (records.hasNext()) {
            String etag = records.getArticleId();
            response.setHeader("ETAG", etag);
            br = records.next();
            String line;
            while ((line = br.readLine()) != null) {
                out.println(line);
            }
        }

        out.close();
        srv.close();
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding(DEFAULT_ENCODING);
        response.setContentType(CONTENT_TYPE);
        NNTPService srv = new NNTPService("localhost", 7500, "xutj@nec-as.nec.com.cn", "eds321");
        srv.init();
        String group = request.getParameter("group");
        NNTPService.NewsWriter nw = srv.postNews(group);
        if (nw == null) {
            logger.severe("News Writer is null failed to post");
            response.setStatus(404);
        }
        response.setHeader("cache-control", "no-cache");
        BufferedWriter output = nw.next();
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), DEFAULT_ENCODING));
        String line = null;
        while ((line = br.readLine()) != null) {
            output.write(line);
            output.newLine();
        }
        output.close();
        nw.close();
        srv.close();
        response.setStatus(201);
    }
}
